﻿$NL.defined("NengLong.Util", function () {
    $NL.cls("static", function () {
        /* 通用函数 */
        window.isUndefined = function (obj) {
            return typeof (obj) == "undefined";
        }
        window.isNull = function (obj) {
            return typeof (obj) == "undefined" || obj == null;
        }
        window.string = {
            format: function () {
                if (!arguments[0]) {
                    return "";
                }
                if (arguments.length == 1) {
                    return arguments[0];
                }
                else if (arguments.length >= 2) {

                    for (var i = 1; i < arguments.length; i++) {
                        arguments[0] = arguments[0].replace(new RegExp("\\{" + (i - 1) + "\\}", "gm"), arguments[i]);
                    }
                    return arguments[0].replace(new RegExp("\\{", "gm"), "{").replace(new RegExp("\\}", "gm"), "}");
                }
            },
            htmlDecode: function (input) {
                return input.replace(/&amp;/g, '&').replace(/&quot;/g, '\"').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
            },
            htmlEncode: function (input) {
                return input.replace(/&/g, '&amp').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
            },
            fromObj: function (o) {
                var arr = [];
                var fmt = function (s) {
                    if (typeof s == 'object' && s != null) {
                        //对数组对象[]的处理 by gzq 2013-10-31
                        if (s.hasOwnProperty("length")) {
                            var retStr = "[";
                            for (var k = 0; k < s.length; k++) {
                                if (k == 0) retStr += string.fromObj(s[k]);
                                else retStr += "," + string.fromObj(s[k]);
                            }
                            return retStr + "]";
                        }
                        return string.fromObj(s);
                    }
                    return /^(string|number)$/.test(typeof s) ? '"' + s + '"' : s;
                };
                if (o.hasOwnProperty("length")) {
                    return fmt(o);
                } else {
                    for (var i in o) {
                        arr.push('"' + i + '":' + fmt(o[i]));
                    }
                    return '{' + arr.join(',') + '}';
                }
            }
        };
        this.Array = {
            find: function () {
                var arr = arguments[0];
                for (var i = 0; i < arr.length; i++) {
                    if (arguments.length == 2 && arr[i] == arguments[1]) {
                        return arr[i];
                    }
                    else if (arguments.length == 3 && $.isPlainObject(arr[i]) && arr[i][arguments[1]] == arguments[2]) {
                        return arr[i]
                    }
                }
            }
        }
        /**
         *  日期时间操作
         *
         */
        this.DateTime = {
            format: function (dt, format) {
                var o = {
                    "M+": dt.getMonth() + 1, //month
                    "d+": dt.getDate(), //day
                    "h+": dt.getHours(), //hour
                    "m+": dt.getMinutes(), //minute
                    "s+": dt.getSeconds(), //second
                    "q+": Math.floor((dt.getMonth() + 3) / 3), //quarter
                    "S": dt.getMilliseconds() //millisecond
                };
                if (/(y+)/.test(format)) {
                    format = format.replace(RegExp.$1, (dt.getFullYear() + "").substr(4 - RegExp.$1.length));
                }
                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(format)) {
                        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                    }
                }
                return format;
            },
            /**
             *  获取当前的日期
             *  默认格式 yyyy-MM-dd
             *  return  以字符串形式返回该日期
             * */
            getNowDateStr: function (format) {
                if (!!format) format = 'yyyy-MM-dd';
                var d = new Date();
                return this.format(d, format);
            }
        }
        this.Convert = {
            toInt: function (obj, defaultValue) {
                var value = (typeof (defaultValue) == "undefined" || defaultValue == null || !$.isNumeric(defaultValue)) ? 0 : defaultValue;
                if ($.isNumeric(obj)) {
                    value = parseInt(obj);
                }
                return value;
            },
            toNumeric: function (strNumeric, dafaultValue) {
                var v = (typeof (defaultValue) == "undefined" || defaultValue == null || !$.isNumeric(defaultValue)) ? 0 : defaultValue;
                if ($.isNumeric(strNumeric)) {
                    v = parseFloat(strNumeric);
                }
                return v;
            },
            toBool: function (obj, defaultValue) {
                var value = (typeof (defaultValue) == "undefined" || defaultValue == null) ? false : defaultValue;
                if (obj != null && obj != undefined) {
                    var temp = $.trim(obj.toString()).toLocaleLowerCase();
                    if (temp === "true") value = true;
                    else if (temp === "false") value = false;
                }
                return value;
            },
            toValueText: function (value, text, parentValue) {
                var vt = {};
                vt.Value = value;
                vt.Text = text;
                vt.ParentValue = parentValue;
                return vt;
            },
            /**
             * 将list的指定项strValue、strText转换成[{Value:"",Text:"",ParentValue:""}...],
             * isHasTop为true,增加置顶项
             * @param list
             * @param strValue
             * @param strText
             * @param strParentValue
             * @param isHasTop
             * @param topValue
             * @param topText
             * @returns {Array}
             */
            toValueTextList: function (list, strValue, strText, strParentValue, isHasTop, topValue, topText) {
                if (!list || list.length <= 0) return [];
                if (isNull(topValue)) topValue = '0';
                if (isNull(topText)) topText = '';

                var vts = [];
                if (!!isHasTop) {
                    vts.push(this.toValueText(topValue, topText, "-1"));
                }
                for (var i = 0; i < list.length; i++) {
                    vts.push(this.toValueText(list[i][strValue], list[i][strText], !!list[i][strParentValue] ? list[i][strParentValue] : "0"));
                }
                if (!!isHasTop) {
                    if (vts.length > 1) {
                        vts[0].ParentValue = vts[1].ParentValue;
                    }
                }
                return vts;
            }
        };
        this.alert = function (msg, title, closeButtonClick) {
            if (!msg) msg = '';
            if (!title) title = '信息提示';
            if (!$.isFunction(closeButtonClick)) closeButtonClick = null;

            var modalFormId = 'modalForm_alert_NengLongUtil';
            var modalFormSelector = string.format('[data-id="{0}"]', modalFormId);
            if ($(modalFormSelector).length <= 0) {
                //如果不存在data-id为modalFormNengLongUtil的div，往body上append
                var html = '';
                html += string.format('<div data-id="{0}" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">', modalFormId);
                html += '    <div class="modal-header">';
                html += '        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>';
                html += string.format('        <h3>{0}</h3></div>', title);
                html += string.format('    <div class="modal-body"><p>{0}</p></div>', msg);
                html += '    <div class="modal-footer">';
                html += '        <button class="btn" data-dismiss="modal" aria-hidden="true" modal-form-button-type="close">关闭</button>';
                html += '    </div>';
                html += '</div>';

                $('body').append(html);
            }

            var modalFormBodySelector = string.format('{0} .modal-body p', modalFormSelector);
            var modalFormTitleSelector = string.format('{0} h3', modalFormSelector);
            $(modalFormBodySelector).html(msg);
            $(modalFormTitleSelector).html(title);

            var closeBtnSelector = string.format('{0} .modal-footer button[modal-form-button-type="close"]', modalFormSelector);
            $(closeBtnSelector).off('click');
            if (!!closeButtonClick) {
                $(closeBtnSelector).on('click', closeButtonClick);
            }

            var option = {backdrop: 'static'};
            $(modalFormSelector).modal(option);
        };
        /**
         * 确认对话框
         * @param msg {string} 提示信息内容
         * @param title {string} 提示信息标题
         * @param submitButtonClick {function()} 确认按钮执行的回调
         * @param closeButtonClick {function()} 取消按钮执行的回调
         */
        this.confirm = function (msg, title, submitButtonClick, closeButtonClick) {
            if (!msg) msg = '';
            if (!title) title = '信息提示';
            if (!$.isFunction(submitButtonClick)) submitButtonClick = null;
            if (!$.isFunction(closeButtonClick)) closeButtonClick = null;

            var modalFormId = 'modalForm_confirm_NengLongUtil';
            var modalFormSelector = string.format('[data-id="{0}"]', modalFormId);
            if ($(modalFormSelector).length <= 0) {
                //如果不存在data-id为modalFormNengLongUtil的div，往body上append
                var html = '';
                html += string.format('<div data-id="{0}" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">', modalFormId);
                html += '    <div class="modal-header">';
                html += '        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>';
                html += string.format('        <h3 id="myModalLabel">{0}</h3></div>', title);
                html += string.format('    <div class="modal-body"><p>{0}</p></div>', msg);
                html += '    <div class="modal-footer">';
                html += '        <button class="btn btn-primary" modal-form-button-type="submit">确定</button>';
                html += '        <button class="btn" data-dismiss="modal" aria-hidden="true" modal-form-button-type="close">取消</button>';
                html += '    </div>';
                html += '</div>';

                $('body').append(html);
            }

            var modalFormBodySelector = string.format('{0} .modal-body p', modalFormSelector);
            var modalFormTitleSelector = string.format('{0} h3', modalFormSelector);
            $(modalFormBodySelector).html(msg);
            $(modalFormTitleSelector).html(title);

            var submitBtnSelector = string.format('{0} .modal-footer button[modal-form-button-type="submit"]', modalFormSelector);
            $(submitBtnSelector).off('click');
            if (!!submitButtonClick) {
                $(submitBtnSelector).on('click', function () {
                    var flag = submitButtonClick();
                    flag = NengLong.Util.Convert.toBool(flag, true);
                    if (flag) {
                        $(this).closest('.modal').modal('hide');
                    }
                });
            }

            var closeBtnSelector = string.format('{0} .modal-footer button[modal-form-button-type="close"]', modalFormSelector);
            $(closeBtnSelector).off('click');
            if (!!closeButtonClick) {
                $(closeBtnSelector).on('click', closeButtonClick);
            }

            var option = {backdrop: 'static'};
            $(modalFormSelector).modal(option);
        };
        this.Form = {
            /**
             * 设置指定对象的所有属性值为null
             * @param obj
             * @returns {{object}} 返回设置好属性值的对象
             */
            setPropNull: function (obj) {
                var o = {};
                $.each(obj, function (key, value) {
                    o[key] = null;
                });
                return o;
            }
        };
        this.Cookie = {
            setCookie: function (name, value)//两个参数，一个是cookie的名子，一个是值
            {
                var Days = 30; //此 cookie 将被保存 30 天
                var exp = new Date();    //new Date("December 31, 9998");
                exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
                document.cookie = name + "=" + decodeURI(value) + ";expires=" + exp.toGMTString();
            },
            getCookie: function (name)//取cookies函数
            {
                var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
                if (arr != null) return decodeURIComponent(arr[2]);
                return null;

            },
            delCookie: function (name)//删除cookie
            {
                var exp = new Date();
                exp.setTime(exp.getTime() - 1);
                var cval = this.getCookie(name);
                if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
            }
        }
        this.LocalStorage = {
            setItem: function (key, value) {
                var ua = NengLong.Util.getMyBrowser();
                if (ua.indexOf("IE:6") > -1 && ua.indexOf("IE:7") > -1) {
                    NengLong.Util.Cookie.setCookie(key, value);
                } else {
                    window.localStorage.setItem(key, value);
                }
            },
            getItem: function (key) {
                var ua = NengLong.Util.getMyBrowser();
                if (ua.indexOf("IE:6") > -1 && ua.indexOf("IE:7") > -1) {
                    return NengLong.Util.Cookie.getCookie(key);
                } else {
                    return window.localStorage.getItem(key);
                }
            },
            removeItem: function (key) {
                var ua = NengLong.Util.getMyBrowser();
                if (ua.indexOf("IE:6") > -1 && ua.indexOf("IE:7") > -1) {
                    NengLong.Util.Cookie.delCookie(key);
                } else {
                    window.localStorage.removeItem(key);
                }
            },
            UserData: {
                userData: null,
                name: location.hostname,
                //this.name = "css88.com";
                init: function () {
                    if (!NengLong.Util.LocalStorage.UserData.userData) {
                        try {
                            NengLong.Util.LocalStorage.UserData.userData = document.createElement('INPUT');
                            NengLong.Util.LocalStorage.UserData.userData.type = "hidden";
                            NengLong.Util.LocalStorage.UserData.userData.style.display = "none";
                            NengLong.Util.LocalStorage.UserData.userData.addBehavior("#default#userData");
                            document.body.appendChild(NengLong.Util.LocalStorage.UserData.userData);
                            var expires = new Date();
                            expires.setDate(expires.getDate() + 365);
                            NengLong.Util.LocalStorage.UserData.userData.expires = expires.toUTCString();
                        } catch (e) {
                            return false;
                        }
                    }
                    return true;
                },

                setItem: function (key, value) {

                    if (NengLong.Util.LocalStorage.UserData.init()) {
                        NengLong.Util.LocalStorage.UserData.userData.load(NengLong.Util.LocalStorage.UserData.name);
                        NengLong.Util.LocalStorage.UserData.userData.setAttribute(key, value);
                        NengLong.Util.LocalStorage.UserData.userData.save(NengLong.Util.LocalStorage.UserData.name);
                    }
                },

                getItem: function (key) {
                    if (NengLong.Util.LocalStorage.UserData.init()) {
                        NengLong.Util.LocalStorage.UserData.userData.load(NengLong.Util.LocalStorage.UserData.name);
                        return NengLong.Util.LocalStorage.UserData.userData.getAttribute(key)
                    }
                },

                removeItem: function (key) {
                    if (NengLong.Util.LocalStorage.UserData.init()) {
                        NengLong.Util.LocalStorage.UserData.userData.load(NengLong.Util.LocalStorage.UserData.name);
                        NengLong.Util.LocalStorage.UserData.userData.removeAttribute(key);
                        NengLong.Util.LocalStorage.UserData.userData.save(NengLong.Util.LocalStorage.UserData.name);
                    }

                }
            }
        }
        this.getMyBrowser = function () {
            var Sys = {};
            var ua = navigator.userAgent.toLowerCase();
            var s;
            (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
                (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
                    (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
                        (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
                            (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;

            if (Sys.ie) return ('IE:' + Sys.ie);
            if (Sys.firefox) return ('Firefox:' + Sys.firefox);
            if (Sys.chrome) return ('Chrome:' + Sys.chrome);
            if (Sys.opera) return ('Opera:' + Sys.opera);
            if (Sys.safari) return ('Safari:' + Sys.safari);
        }
    });
    $NL.cls("static Url", function () {

        function regEx(url) {
            if (typeof (url) == "undefined") url = NengLong.Util.Url.getCurrentUrl();
            //如果加上/g参数，那么只返回$0匹配。也就是说arr.length = 0
            var re = /(\w+):\/\/([^\:|\/]+)(\:\d*)?(.*\/)([^#|\?|\n]+)?(#.*)?(\?.*)?/i;
            //re.exec(url);
            var arr = url.match(re);
            return arr;
        };
        this.getCurrentUrl = function () {
            return window.location.href;
        }
        this.getHost = function (url) {
            var arr = regEx(url);
            return typeof (arr[2]) == "undefined" ? "" : arr[2];
        };
        this.getPath = function (url) {
            var arr = regEx(url);
            return typeof (arr[4]) == "undefined" ? "" : arr[4];
        };
        this.getFileName = function (url) {
            var arr = regEx(url);
            return typeof (arr[5]) == "undefined" ? "" : arr[5];
        };
        this.getQueryString = function (url) {
            var arr = regEx(url);
            var str = typeof (arr[7]) == "undefined" ? '' : arr[7];
            str += typeof (arr[6]) == "undefined" ? '' : arr[6];
            if (str.indexOf("#!") >= 0)
                return str.replace("#!", "&");
            else if (str.indexOf("#") >= 0)
                return str.replace("#", "&");
            else
                return str;
        };
        this.getQueryParam = function (name, url) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var sUrl = sUrl = this.getQueryString(url);
            var r = sUrl.replace("?", "").match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        };

        //获取参数列表
        this.getQueryParams = function (url) {
            var queryString = this.getQueryString(url);
            if (queryString.length > 1) {
                // 获取链接中参数部分
                if (queryString.indexOf("?") >= 0) {
                    queryString = queryString.substring(queryString.indexOf("?") + 1);
                }
                // 分离参数对 ?key=value&key2=value2
                var parameters = queryString.split("&");
                if (parameters.length > 0) {
                    var pos, paraName, paraValue;
                    var qs = {};
                    var qstr = '';
                    for (var i = 0; i < parameters.length; i++) {
                        // 获取等号位置
                        pos = parameters[i].indexOf('=');
                        if (pos == -1) {
                            continue;
                        }

                        qstr += ',\"' + parameters[i].substring(0, pos) + '\":\"' + parameters[i].substring(pos + 1) + '\"';
                    }
                    if (qstr.length > 1) {
                        qstr = '{' + qstr.substring(1) + '}';
                        qs = eval("(" + qstr + ")");
                        return qs;
                    }
                }
            }
            return null;
        };
        //根据参数创建url
        this.createUrl = function (params, url) {
            if (typeof (url) == "undefined") {
                url = NengLong.Util.Url.getCurrentUrl();
            }
            var fUrl = url;

            if (url.indexOf("?") >= 0) {
                fUrl = url.substring(0, url.indexOf("?") + 1);
            }
            else if (url.indexOf("#") >= 0) {
                fUrl = url.substring(0, url.indexOf("#") + 1);
            }
            else {
                fUrl = fUrl + "#";
            }
            var p = NengLong.Util.Url.getQueryParams(url);
            if (p == null) p = {};
            $.extend(p, params);
            var search = "";
            $.each(p, function (n, v) {
                if (search == "")
                    search = n + "=" + v;
                else
                    search = search + "&" + n + "=" + v;
            });
            return fUrl + search;
        }
    });
})
;
